<template>
    <el-dialog
      :title="roleForm.id ? '修改目录' : '新增目录'"
      :visible="visible"
      width="30%"
      @close="closeDialog"
      @open="openDialog">
      <el-form :model="roleForm" :rules="roleRules" ref="roleRef" label-width="100px">
        <el-form-item label="所属学科" v-if="!$route.query.id" prop="subjectID">
          <el-select v-model="roleForm.subjectID" placeholder="请选择" style="width:100%">
            <el-option
            v-for="item in subjectOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value">
            </el-option>
          </el-select>
          <!-- <el-input v-model="roleForm.subjectName"></el-input> -->
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="roleForm.directoryName" placeholder="请输入目录名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button @click="$emit('dialog-close')">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
</template>

<script>
import { update, add, detail } from '@/api/hmmm/directorys.js'
import { simple } from '@/api/hmmm/subjects'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
   } 
  },
  data() {
    return {
      roleForm: {
        subjectID: '', // 所属学科
        directoryName: '' // 目录名称
      },
      roleRules: {
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'blur' }
        ],
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      },
      subjectOptions: []
    }
  },
  // 所属学科下拉框
  async created() {
    const res = await simple()
    // console.log(res);
    this.subjectOptions = res.data
    this.$emit('fetch-directorys-list')
  },
  methods: {
    // 弹窗打开
    openDialog() {
      this.$emit('fetch-directorys-list')
    },
    // 当点击 x 和蒙版时，弹窗关闭时，都会触发的事件
    closeDialog() {
      this.$emit('dialog-close')
      // 清空表单内容
      this.$refs.roleRef.resetFields()
    },
    // 新增目录
    submit() {
      // 兜底校验
      this.$refs.roleRef.validate(async valid => {
        if (!valid) return
        // 校验通过
        if (this.roleForm.id) {
          // 修改
          await update(this.roleForm)
        } else {
          // 新增
          await add(this.roleForm)
        }
        // 提示用户
        const msg = this.roleForm.id ? '修改目录成功' : '新增目录成功'
        this.$message.success(msg)
        // 关闭弹窗
        this.closeDialog()
        // 刷新列表
        this.$emit('fetch-directorys-list')
      })
    },
    // 获取列表详情（数据回显）
    async fetchdirectorysDetail(id) {
      const res = await detail(id)
      // console.log(res);
      this.roleForm = res.data
    }
  }
}
</script>

<style scoped lang='less'></style>
